﻿using System;
using System.IO;
using System.Web.Mvc;
using Netkk.Common.Models;

namespace Netkk.Core.ActionResults
{
    public class DownloadResult : ActionResult
    {
        public Download Download { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            // verify properties 
            if (Download == null)
            {
                throw new ArgumentNullException("Download");
            }

            string path = context.HttpContext.Server.MapPath(Path.Combine("~/App_Data/Files/Downloads/", Download.FileName));
            if (!File.Exists(path)) return;

            context.HttpContext.Response.Clear();
            context.HttpContext.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", Path.GetFileName(path)));
            context.HttpContext.Response.ContentType = Download.ContentType;

            using (FileStream fs = File.OpenRead(path))
            {
                WriteToStream(fs, context.HttpContext.Response.OutputStream);
            }
            context.HttpContext.Response.End();
        }

        protected virtual void WriteToStream(Stream inputStream, Stream outputStream)
        {
            int bufferLen = 1024;
            byte[] buffer = new byte[bufferLen];
            int readLen;

            while ((readLen = inputStream.Read(buffer, 0, bufferLen)) > 0)
            {
                outputStream.Write(buffer, 0, readLen);
                outputStream.Flush();
            }

        }
    }
}